﻿using Ecommerce.Areas.Manager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce.Common;

namespace Ecommerce.Areas.Home.Controllers
{
    public class CartController : Controller
    {
        //
        // GET: /Home/Cart/

        private DatabaseContext db = new DatabaseContext();

        public ActionResult Index()
        {
            List<Product> lstP = Session[EConst.LIST_CART_NAME] == null ? new List<Product>() : (List<Product>)Session["ListCart"];

            return View(lstP);
        }

        [HttpPost]
        public ActionResult AddCart(string productID)
        {
            int ID = 0;
            try
            {
                ID = Int32.Parse(productID);
            }
            catch
            {
                return RedirectToAction("Index", "Template");
            }

            Product p = db.Products.Find(ID);
            if (p == null)
            {
                return RedirectToAction("Index", "Template");
            }

            List<Product> lstP = Session[EConst.LIST_CART_NAME] == null ? new List<Product>() : (List<Product>)Session[EConst.LIST_CART_NAME];
            lstP.Add(p);
            Session[EConst.LIST_CART_NAME] = lstP;

            if (Session[EConst.COUNT_ITEMS_CART] == null)
            {
                Session[EConst.COUNT_ITEMS_CART] = 1;
                Session[EConst.TOTAL_PRICE_CART] = p.Price;
            }
            else
            {
                decimal totalCart = Decimal.Parse(Session[EConst.TOTAL_PRICE_CART].ToString());
                totalCart += p.Price;
                Session[EConst.TOTAL_PRICE_CART] = totalCart;

                int countCart = Int32.Parse(Session[EConst.COUNT_ITEMS_CART].ToString());
                countCart++;
                Session[EConst.COUNT_ITEMS_CART] = countCart;
            }

            return RedirectToAction("Index");

        }

        public ActionResult Remove(string prodID)
        {
            int ID = 0;
            try
            {
                ID = Int32.Parse(prodID);
            }
            catch
            {
                return RedirectToAction("Index", "Template");
            }

            List<Product> lstP = Session["ListCart"] == null ? new List<Product>() : (List<Product>)Session["ListCart"];
            lstP.RemoveAt(ID);
            Session["ListCart"] = lstP;

            return RedirectToAction("Index");
        }

    }
}
